package com.rechaege.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.entity.Customer;
import com.entity.Recharge;
import com.interfaces.CustomerDao;
import com.interfaces.CustomerMeterDao;
import com.interfaces.MeterDao;
import com.interfaces.RechargeDao;
import com.interfaces.SysdicDao;
import com.setting.service.SysdicService;
import com.utils.JsonResult;

/**   
* @Title: RechargeService.java 
* @Package com.rechaege.service 
* @author 孙梦楠 
* @date 2017年11月7日 下午1:02:41 
* @version V1.0.0   
*/
@Service
public class RechargeService {
	
	@Autowired
	private RechargeDao rechargedao;

	@Autowired
	private CustomerDao customerdao;



	@Autowired
	private SysdicDao sysdicdao;

	@Autowired
	private CustomerMeterDao customermeterdao;

	@Autowired
	private MeterDao meterdao;

	@Autowired
	private SysdicService sysdicservice;

	
	// 充值
		@Transactional
		public JsonResult<Recharge> recharge(Integer customerid, Double money) {

			if (money == null) {
				return new JsonResult<Recharge>(512, "充值失败..金额错误", null);

			} else {

				Recharge recharge = new Recharge();
				recharge.setCustomerid(customerid);
				Customer customer = customerdao.findOne(customerid);
				Integer meterid = customermeterdao.findByCustomerid2(customerid).getPk().getMeterid();
				recharge.setMeterid(meterid);
				recharge.setCustomeraccount(customer.getCustomeraccount());
				recharge.setCustomername(customer.getCustomername());
				recharge.setCustomeraddress(customer.getCustomeraddress());
				recharge.setCustomerorg(customer.getCustomerorg());
				recharge.setCustomertype(customer.getCustomertype());
				recharge.setDirection("购电");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String issuetime = sdf.format(new Date());
				recharge.setIssuetime(issuetime);
				if(rechargedao
						.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0).size()==0) {
					recharge.setFrequency(1);
					
				}else {
				Integer frequency = rechargedao
						.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0).get(0)
						.getFrequency();
				frequency++;
				recharge.setFrequency(frequency);
				}
				/*
				 * beforemoney 调用接口 aftermoney 接口
				 */

				recharge.setMoney(money);
//				Double totalmoney = rechargedao
//						.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0).get(0)
//						.getTotalmoney();
//				recharge.setTotalmoney(totalmoney);

				recharge.setOptstatus("等待下发");
				recharge.setOptnum(0);

				rechargedao.save(recharge);
				return new JsonResult<Recharge>(512, "充值命令已下发", recharge);
			}
		}
}
